var hasRows = false;
var rowQuantity = 0;
(function($){
 $.fn.editable = function(options) {

  var defaults = {   
   columns:{},
   defaultColumn:{
        size:10,
        defaultClass: 'fondo_txtbox128'
   }
  };
  var options = $.extend(defaults, options);
  var tempBean = new Array();
  var _tempBean = new Array();
  var inclusoBean = {numDocu:'',descripcion:'',codMon:'',importe:'',estado:true};
  var _inclusoBean = {numDocu:'',descripcion:'',codMon:'',importe:'',estado:true};
  var editarButton = "<a href='#' class='link link_editar' title='Editar'><span class='ui-icon ui-icon-pencil' style='float: left; margin: 0 1px;'/></a>";
  var cancelarButton = "<a href='#' class='link link_cancelar' title='Cancelar'><span class='ui-icon ui-icon-cancel' style='float: left; margin: 0 1px;'/></a>";
  var grabarButton = "<a href='#' class='link link_grabar' title='Guardar'><span class='ui-icon ui-icon-disk' style='float: left; margin: 0 1px;'/></a>";
  var eliminarButton = "<a href='#' class='link link_eliminar' title='Eliminar'><span class='ui-icon ui-icon-close' style='float: left; margin: 0 1px;'/></a>";
  var isEditingSomeRow = false;  
  /*
    variable creada para almacenar de todas las filas en valores temporales
  */
  var _rowValues = new Array();
  var _values = new Array();
  var $values = new Array();
  var rowValues = new Array();
  var columnsConfig = new Array();
  var count = 0;
  var numberOfColumn = 0;
  var col1 = "<input type='text' class='"+defaults.defaultColumn.defaultClass+"'/>";
  var col2 = "<input type='text' class='"+defaults.defaultColumn.defaultClass+"'/>";
  var col3 = "<input type='text' class='"+defaults.defaultColumn.defaultClass+"'/>";
  var col4 = "<input type='text' class='"+defaults.defaultColumn.defaultClass+"'/>";
  var hasColumns = false;
  columns=options.columns;
  
  function addRow(obj){    
    var col5 =  grabarButton;
    var nextrowid = 0;
    if(obj.find("tbody tr:last").attr("rowid")!=null)
        nextrowid = parseInt(obj.find("tbody tr:last").attr("rowid"))+1;
    else
        nextrowid = 0;
    var newTr = '<tr rowid="'+nextrowid+'">';    
    $.each(columns, function(count, item) {
        newTr += '<td></td>';        
    });
    newTr += '<td></td></tr>';
    
    obj.find("tbody").append(newTr);
    row = obj.find("tbody tr:last");
    row.addClass("new").addClass("edit");
    previewToEdit(row);
    _inclusoBean = null;
    row.find("td:last").html(grabarButton);
  }
  
  function previewToEdit(row){
    count=0;
    _inclusoBean = {numDocu:'',descripcion:'',codMon:'',importe:'',estado:true};
    row.children(":not(:last-child)").each(function(){
        var col = $(this);
        tempBean[count] = col.html();        
        var type = columns[count].type;
        var input = '';
        var styleClass = columns[count].styleClass;
        var maxlength =columns[count].maxLength;
        var size=columns[count].size;
        var id = columns[count].id;            
        if(styleClass==null||styleClass.length==0)
            styleClass = defaults.defaultColumn.defaultClass;
        if(maxlength!=null)
            maxlength = " maxlength='"+columns[count].maxLength+"' ";
        if(size!=null)
            size = " size='"+columns[count].size+"' ";
        else
            size='';
        if(type == 'text'){
            input= "<input type='"+type+"' id='"+id+"' class='"+styleClass+"' value='"+col.html()+"'"+maxlength+" "+size+"/>";                        
        }
        if(type == 'select'){
            var dataLength = columns[count].data.length;
            var data = columns[count].data;
            input = "<select id='"+id+"' class='"+styleClass+"'>";            
            options = '';       
            if(_values[count]){
                var tipUnidMone  = _values[count].tipUnidMone;
                var desTipUnidMone = _values[count].desTipUnidMone;
            }
            var selected = '';
            for (var i = 0; i < dataLength; i++) {
                var singleData = data[i];
                var codTipo = '';
                var desTipo = '';
                var singleDataPropertyCount = 0;
                for(var n in singleData){                        
                    if(singleDataPropertyCount==1){
                        codTipo = singleData[n];
                        if(codTipo == tipUnidMone)
                            selected= 'selected';
                    }
                    if(singleDataPropertyCount==2)
                        desTipo = singleData[n];
                    singleDataPropertyCount++;
                }
                options += '<option value="' + singleData.codigo + '" '+selected+'>' + singleData.descripcion+'</option>';
                selected = '';
            }
            input = input + options +"</select>";            
        }        
        col.html(input);
        $("#"+id).bestupper(); 
        $(".numeric").blur(function(){
            extractNumber(this,2,false);
        });
        $(".numeric").keyup(function(){
            extractNumber(this,2,false);
        });       
        $(".numeric").keypress(function(event){
            blockNonNumbers(this, event, true, false);
        });        
        count ++;
    });    
  }
  
  return this.each(function() {
    obj = $(this);
    
    
    $('.link_editar').live('click',function(){        
        if(isEditingSomeRow){
            alert("No puede editar mas de una fila a la vez");
            return false;
        }        
        var row = $(this).parents("tr:first");
        var rowid = row.attr("rowid");
        _rowValues[rowid] = new Array();
        count = 0;
        row.children(":not(:last-child)").each(function(){
            var col = $(this);            
            _rowValues[rowid][count] = col.html();            
            count++;
        });
        console.log(_rowValues);
        row.removeClass("saved").addClass("edit");
        previewToEdit(row);
        row.find("td:last",obj).html(grabarButton+cancelarButton);
        isEditingSomeRow = true;
        if(rowQuantity>0)
                hasRows = true;
      });
      
      $('.link_grabar').live('click',function(){
        var row = $(this).parents("tr:first");
        count = 0;
        var incorrectInput = false;
        row.children(":not(:last-child)").each(function(){
            var col = $(this);
            var type = columns[count].type;
            if(type=='text'){
                _value = col.find("input").attr("value"); 
                if(_value==""){
                    alert("Este dato es obligatorio");
                    col.find("input").focus();
                    incorrectInput = true;
                    return false;
                }
            }
            
        });
        if(incorrectInput)
            return false;                
        var row = $(this).parents("tr:first");
        var hasClassNew = row.hasClass("new");
        try{
            rowQuantity = 1;//jsonrpc.jsonService.inclusosToSession(inclusoBean);
        }catch(e){
            alert("Lo sentimos ocurrio un error, por favor intentelo nuevamente...");
            return false;
        }
        row.removeClass("edit").removeClass("new").addClass("saved").addClass("wordbreak");
        count = 0;
        row.children(":not(:last-child)").each(function(){
            var col = $(this);
            var type = columns[count].type;
            var _value = '';       
            var _valueToBean = '';
            if(type=='text'){
                _value = col.find("input").attr("value");
                _values[count] = _value;
                _valueToBean = _value;
            }
            if(type=='select'){
                try{
                    _values[count] = new Array();
                    _values[count].tipUnidMone = col.find("select option:selected").attr("value");                
                    _values[count].desTipUnidMone= col.find("select option:selected").text();
                    _value =  _values[count].desTipUnidMone;        
                    _valueToBean = col.find("select option:selected").attr("value");    
                }catch(e){                    
                }
            }
            col.html(_value);
            tempBean[count] = _valueToBean;            
            count++;
        });        
        row.find("td:last").html(editarButton+eliminarButton);        
        
        if(rowQuantity>0)
            hasRows = true;
        isEditingSomeRow = false;
        var needRow = (obj.find(".new").length==0&&obj.find(".edit").length==0);
        if(needRow)
            addRow(obj);        
      });
      
      $('.link_cancelar').live('click',function(){        
        var row = $(this).parents("tr:first");
        row.removeClass("edit").removeClass("new").addClass("saved").addClass("wordbreak");
        count = 0;
        row.children(":not(:last-child)").each(function(){            
            var col = $(this);            
            var type = columns[count].type;
            var _value = _values[count];
            if(type=='select'){
                _value = _values[count].desTipUnidMone;
            }            
            col.html(_value);
            count ++;
        });    
        row.find("td:last").html(editarButton+eliminarButton);
        isEditingSomeRow = false;
        if(rowQuantity>0)
                hasRows = true;
        $("#numDocu").focus();
      });
      
      $('.link_eliminar').live('click',function(){
        var row = $(this).parents("tr:first");
        count = 0;
        inclusoBean = {numDocu:'',descripcion:'',codMon:'',importe:'',estado:true};
        tempBean = new Array();
        row.children(":not(:last-child)").each(function(){
            var col = $(this);
            tempBean[count] = col.html();            
            count++;
        });
        rowQuantity = jsonrpc.jsonService.removeInclusosFromSession(inclusoBean);               
        row.remove();
        if(rowQuantity>0){
            hasRows = true;
            }
        else {
         hasRows = false;
        }
            
        $('#idCantIncl').html(rowQuantity + " incluso(s)") ;
      });
    
    
    var rows = obj.find("tr");
    var rowsSaved = $('.saved',obj);
    rowsSaved.each(function(){
        var row = $(this);
        row.find("td:last",obj).html(editarButton+eliminarButton);
    });
    addRow(obj);
  });
 };
})(jQuery);